package com.fxwater.websocket.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.fxwater.biz.domain.PumpStationInfo;
import com.fxwater.common.utils.DateUtils;
import com.fxwater.websocket.service.SelectDataInfo;
import com.fxwater.websocket.util.SpringBeanFinder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class SelectDataInfoImpl implements SelectDataInfo {

    JdbcTemplate jdbcTemplate = SpringBeanFinder.findBean(JdbcTemplate.class);

    private final String DATE_FORMAT = "yyyyMMddHHmm";

    private final DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);

    private Logger logger = LoggerFactory.getLogger(SelectDataInfoImpl.class);

    @Override
    public List<Map<String, Object>> selectItemInfoByPumpCode(String pumpCode){
        String sql = "select item_name,item_code from fx_item where pump_code = '" + pumpCode + "'";
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql);
        return resultList;
    }

    @Override
    public List<Map<String, Object>> selectPumpStationInfoList() {
        String sql = "select * from fx_pump_station";
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql);
        return resultList;
    }

    @Override
    public List<Map<String, Object>> selectInfo(String item, String itemCode, String time) {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT lastchange datetime,item_code,item_val,")
          .append("(select unit_flag from dbo.fx_item where pump_code ='")
          .append(item).append("' and item_code ='").append(itemCode).append("') unit")
          .append(" FROM dbo.fx_history_data WHERE item_code = '").append(itemCode)
          .append("' AND lastchange = '").append(time).append("'");
        System.out.println(sql.toString());
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql.toString());
        for(Map<String, Object> map : resultList){
            String dateTime = map.get("datetime").toString();
            if(dateTime.contains(".")){
                dateTime = dateTime.split("\\.")[0];
            }
            map.put("datetime", dateTime);
            DecimalFormat decimalFormat = new DecimalFormat(".#");
            double itemVal =Double.parseDouble(decimalFormat.format(Double.parseDouble(map.get("item_val").toString())));
            map.put("item_val", itemVal);
        }
        return resultList;
    }

    public List<Map<String, Object>> selectByTime(String pumpCode, String itemCode, String startTime, String endTime, String timeDimension) {

        List<Map<String, Object>> data = new ArrayList<>();
        Date startDateTime = null;
        Date endDateTime = null;
        try {
            if(StrUtil.isNotBlank(startTime)){
                startDateTime = dateFormat.parse(startTime);
            }
            if(StrUtil.isNotBlank(endTime)){
                endDateTime = dateFormat.parse(endTime);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(startDateTime==null && endDateTime!=null){
            startDateTime = DateUtil.offset(endDateTime, DateField.DAY_OF_YEAR,-3) ;
        }

        if(endDateTime==null && startDateTime!=null){
            endDateTime = DateUtil.offset(startDateTime, DateField.DAY_OF_YEAR,3) ;
        }

        if(startDateTime.getTime()>endDateTime.getTime()){
            Date temp = startDateTime;
            startDateTime = endDateTime;
            endDateTime = temp;
        }

        long beginIndex = DateUtil.endOfWeek(startDateTime).getTime()/ 1000 / 3600 / 24 / 7;
        logger.info("开始时间是{}，开始时间的时间戳是{}，存储的分区表编号是{}",startDateTime,startDateTime.getTime(),beginIndex);

        long endIndex = DateUtil.endOfWeek(endDateTime).getTime() / 1000 / 3600 / 24 / 7;
        logger.info("结束时间是{}，结束时间的时间戳是{}，存储的分区表编号是{}",endDateTime,endDateTime.getTime(),endIndex);


        if(beginIndex==endIndex){
            List<Map<String, Object>> list = selectDataFromPartitionTable(pumpCode, itemCode, startDateTime, endDateTime, beginIndex);
            data.addAll(list);
        } else {
            for(long index = beginIndex;index<=endIndex;index++){
                List<Map<String, Object>> list = selectDataFromPartitionTable(pumpCode, itemCode, startDateTime, endDateTime, index);
                data.addAll(list);
            }
        }
        data.forEach(map->{
            String itemValue = map.get("item_val")==null?null:String.valueOf(map.get("item_val"));
            if(itemValue.contains("0e")||itemValue.contains("0E")){
                map.put("item_val","0");
            }
        });
        return data;
    }

    private List<Map<String, Object>> selectDataFromPartitionTable(String pumpCode, String itemCode, Date startDateTime, Date endDateTime, long index) {
        String partitionTableName = "fx_history_data_" + index;
        String tableCheckSql ="select count(1) from sysobjects where id=object_id('"+partitionTableName+"') and type = 'U'";
        Integer tableNum = jdbcTemplate.queryForObject(tableCheckSql,Integer.class);
        if(tableNum>0){
            String sql = "SELECT " +
                    "  his.lastchange AS datetime, " +
                    "  his.item_code as item_code, " +
                    "  his.item_val as item_val," +
                    "  i.item_name as item_name, " +
                    "  (case when i.unit_zh is not null then i.unit_zh else i.unit_flag end )as unit " +
                    " FROM " +
                    " fx_history_data_" + index + "  his " +
                    " LEFT JOIN fx_item i ON his.item_code = i.item_code " +
                    " WHERE " +
                    //"i.pump_code=? and "+
                    "  i.item_code =? " +
                    " and  his.lastchange >=? and his.lastchange <=? ";
            logger.info("从表{}中查询{}到{}的数据",partitionTableName,startDateTime,endDateTime);
            return jdbcTemplate.queryForList(sql,itemCode, new Timestamp(startDateTime.getTime()),new Timestamp(endDateTime.getTime()));
        } else {
            return Collections.EMPTY_LIST;
        }

    }
}
